//
//  LBWComposeTextView.swift
//  weibo
//
//  Created by Limonwei on 15/12/14.
//  Copyright © 2015年 heima. All rights reserved.
//

//自定义一个UITextView的属性方法  可以直接在xib中修改的用IBDesignable修饰 以及IBInspectable

//发布微博输入信息的视图
import UIKit

@IBDesignable class LBWComposeTextView: UITextView {
    
    @IBInspectable var placeholder: String? {
        didSet{
            placeholderLabel.text = placeholder
        }
    }
    
    //重写text属性,为了在didSet里显示或者隐藏
    override var text: String? {
        didSet{
            //当有文字输入的时候占位文字隐藏
            placeholderLabel.hidden = hasText()
        }
    }
    //占位文字字体大小
    override var font: UIFont? {
        didSet{
            placeholderLabel.font = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    private func setupUI(){
        
        //添加控件
        addSubview(placeholderLabel)
        //设置约束 用系统的
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -10))
        
        //利用通知监听文字的改变,显示或隐藏占位文字
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
 
    }
    
    //layoutSubview里设置控件的x y 值
    override func layoutSubviews() {
        super.layoutSubviews()
        
        placeholderLabel.x = 5
        placeholderLabel.y = 8
    }
    
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //实现监听方法
    @objc private func textChange(){
        
        placeholderLabel.hidden = hasText()
    }
  
    
    //懒加载一个占位文字控件
    private lazy var placeholderLabel: UILabel = {
    
        //定义一个label
        let label = UILabel()
        //设置换行
        label.numberOfLines = 0
        //设置文字
        label.text = "占位文字"
        //设置字体
        label.font = UIFont.systemFontOfSize(12)
        //设置字体颜色
        label.textColor = UIColor.lightGrayColor()
        
        //返回label
        return label
    
    }()

}































